package com.sjw.workflow.agent;

import com.sjw.workflow.core.WorkflowContext;
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.regex.Pattern;

/**
 * 验证Agent
 * 负责验证数据的完整性和正确性
 */
public class ValidationAgent extends BaseAgent {
    
    // private static final Logger logger = LoggerFactory.getLogger(ValidationAgent.class);
    
    public ValidationAgent() {
        super("validator", "Validation Agent", 
              "Validates data integrity and correctness using various validation rules");
    }
    
    @Override
    protected Map<String, Object> executeInternal(Map<String, Object> input, WorkflowContext context) throws Exception {
        System.out.println("ValidationAgent starting data validation");
        
        Map<String, Object> output = new HashMap<>();
        
        // 获取输入数据
        Object dataToValidate = input.get("data");
        if (dataToValidate == null) {
            throw new IllegalArgumentException("No data provided for validation");
        }
        
        // 执行验证
        Map<String, Object> validationResult = validateData(dataToValidate);
        
        // 生成验证报告
        Map<String, Object> report = generateValidationReport(validationResult);
        
        // 准备输出
        output.put("validationResult", validationResult);
        output.put("validationReport", report);
        output.put("isValid", validationResult.get("isValid"));
        output.put("validationTime", System.currentTimeMillis());
        output.put("status", "success");
        
        // 模拟一些处理时间
        Thread.sleep(800);
        
        System.out.println("ValidationAgent completed data validation");
        return output;
    }
    
    /**
     * 验证数据
     */
    private Map<String, Object> validateData(Object data) {
        Map<String, Object> result = new HashMap<>();
        List<String> errors = new ArrayList<>();
        List<String> warnings = new ArrayList<>();
        boolean isValid = true;
        
        if (data instanceof String) {
            String text = (String) data;
            
            // 验证文本长度
            if (text.length() < 1) {
                errors.add("Text is empty");
                isValid = false;
            } else if (text.length() > 1000) {
                warnings.add("Text is very long (" + text.length() + " characters)");
            }
            
            // 验证文本内容
            if (text.trim().isEmpty()) {
                errors.add("Text contains only whitespace");
                isValid = false;
            }
            
            // 验证特殊字符
            if (containsSpecialCharacters(text)) {
                warnings.add("Text contains special characters");
            }
            
            result.put("textLength", text.length());
            result.put("isEmpty", text.trim().isEmpty());
            result.put("hasSpecialChars", containsSpecialCharacters(text));
            
        } else if (data instanceof List) {
            List<?> list = (List<?>) data;
            
            // 验证列表大小
            if (list.isEmpty()) {
                errors.add("List is empty");
                isValid = false;
            } else if (list.size() > 100) {
                warnings.add("List is very large (" + list.size() + " items)");
            }
            
            // 验证列表元素
            for (int i = 0; i < list.size(); i++) {
                Object item = list.get(i);
                if (item == null) {
                    errors.add("List contains null element at index " + i);
                    isValid = false;
                }
            }
            
            result.put("listSize", list.size());
            result.put("hasNullElements", list.contains(null));
            
        } else if (data instanceof Map) {
            Map<?, ?> map = (Map<?, ?>) data;
            
            // 验证Map大小
            if (map.isEmpty()) {
                errors.add("Map is empty");
                isValid = false;
            }
            
            // 验证Map键值
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                if (entry.getKey() == null) {
                    errors.add("Map contains null key");
                    isValid = false;
                }
                if (entry.getValue() == null) {
                    warnings.add("Map contains null value for key: " + entry.getKey());
                }
            }
            
            result.put("mapSize", map.size());
            result.put("hasNullKeys", map.containsKey(null));
            result.put("hasNullValues", map.containsValue(null));
            
        } else {
            // 验证其他类型
            if (data == null) {
                errors.add("Data is null");
                isValid = false;
            } else {
                warnings.add("Unknown data type: " + data.getClass().getSimpleName());
            }
            
            result.put("dataType", data != null ? data.getClass().getSimpleName() : "null");
        }
        
        result.put("isValid", isValid);
        result.put("errors", errors);
        result.put("warnings", warnings);
        result.put("errorCount", errors.size());
        result.put("warningCount", warnings.size());
        
        return result;
    }
    
    /**
     * 检查是否包含特殊字符
     */
    private boolean containsSpecialCharacters(String text) {
        Pattern specialCharPattern = Pattern.compile("[^a-zA-Z0-9\\s]");
        return specialCharPattern.matcher(text).find();
    }
    
    /**
     * 生成验证报告
     */
    private Map<String, Object> generateValidationReport(Map<String, Object> validationResult) {
        Map<String, Object> report = new HashMap<>();
        
        boolean isValid = (Boolean) validationResult.get("isValid");
        List<String> errors = (List<String>) validationResult.get("errors");
        List<String> warnings = (List<String>) validationResult.get("warnings");
        
        report.put("validationStatus", isValid ? "PASSED" : "FAILED");
        report.put("timestamp", System.currentTimeMillis());
        report.put("summary", String.format("Validation %s with %d errors and %d warnings", 
                isValid ? "passed" : "failed", errors.size(), warnings.size()));
        
        if (!errors.isEmpty()) {
            report.put("criticalIssues", errors);
        }
        
        if (!warnings.isEmpty()) {
            report.put("warnings", warnings);
        }
        
        // 生成建议
        List<String> recommendations = new ArrayList<>();
        if (!isValid) {
            recommendations.add("Fix all critical errors before proceeding");
        }
        if (!warnings.isEmpty()) {
            recommendations.add("Review warnings and consider addressing them");
        }
        if (isValid && warnings.isEmpty()) {
            recommendations.add("Data validation passed successfully");
        }
        
        report.put("recommendations", recommendations);
        
        return report;
    }
}
